package com.at.bilibili.api.aspect;

import com.at.bilibili.api.support.UserSupport;
import com.at.bilibili.domain.annotation.ApiLimitedRole;
import com.at.bilibili.domain.auth.UserRole;
import com.at.bilibili.domain.exception.ConditionException;
import com.at.bilibili.service.UserRoleService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Aspect // 标记为切面类
@Order(1) // 优先级
@Component
public class ApiLimitedRoleAspect {

    @Autowired
    private UserSupport userSupport;
    @Autowired
    private UserRoleService userRoleService;

    // 将切入点 与我们编写的注解进行绑定
    @Pointcut("@annotation(com.at.bilibili.domain.annotation.ApiLimitedRole)")
    public void check(){}

    @Before("check() && @annotation(apiLimitedRole)")
    public void doBefore(JoinPoint joinPoint, ApiLimitedRole apiLimitedRole){
        Long userId = userSupport.getCurrentUserId();
        // 获取当前用户的角色
        List<UserRole> userRoleList = userRoleService.getUserRoleByUserId(userId);
        // 获取需要限制的角色编码列表
        String[] limitedRoleCodeList = apiLimitedRole.limitedRoleCodeList();
        Set<String> limitedRoleCodeSet = Arrays.stream(limitedRoleCodeList).collect(Collectors.toSet());
        Set<String> roleCodeSet = userRoleList.stream().map(UserRole::getRoleCode).collect(Collectors.toSet());
        roleCodeSet.retainAll(limitedRoleCodeSet); // 取交集
        if (roleCodeSet.size() > 0){
            throw new ConditionException("接口权限不足: 权限不足！！！");
        }
    }
}
